﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using System.Runtime.Remoting.Messaging;

namespace EmailComponent
{
    public class Email
    {
        public string Subject { get; set; }
        public string FromEmail { get; set; }
        public string FromName { get; set; }
        public string MessageBody { get; set; }
        public string SmtpServer { get; set; }
        public int SmtpPort { get; set; }
        public NetworkCredential SmtpCredentials { get; set; }

        public bool SendEmail(string toEmail, string toName)
        {
            try
            {
                MailMessage message = new MailMessage();
                message.IsBodyHtml = true;
                message.Priority = MailPriority.Normal;
                message.To.Add(new MailAddress(toEmail, toName));
                message.From = (new MailAddress(this.FromEmail, this.FromName));
                message.Subject = this.Subject;
                message.Body = this.MessageBody;

                SmtpClient sc = new SmtpClient();
                sc.Host = this.SmtpServer;
                sc.Credentials = SmtpCredentials;
                sc.EnableSsl = true;
                sc.Port = this.SmtpPort;
                sc.DeliveryMethod = SmtpDeliveryMethod.Network;
                sc.UseDefaultCredentials = false;
                sc.Timeout = 2000;
                sc.Send(message);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        public delegate bool SendEmailDelegate(string toEmail, string toName);

        public void GetResultsOnCallback(IAsyncResult ar)
        {
            SendEmailDelegate del = (SendEmailDelegate)((AsyncResult)ar).AsyncDelegate;
            try
            {
                bool result = del.EndInvoke(ar);
            }
            catch (Exception ex)
            {
                bool result = false;
            }
        }

        public bool SendEmailAsync(string toEmail, string toName)
        {
            try
            {
                SendEmailDelegate dc = new SendEmailDelegate(this.SendEmail);
                AsyncCallback cb = new AsyncCallback(this.GetResultsOnCallback);
                IAsyncResult ar = dc.BeginInvoke(toEmail, toName, cb, null);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
    }
}
